<template>
  <div class="app-container">
    <div class="config-name">{{ configData.name }}</div>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除</el-button>
      </el-col> -->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table ref="tables" v-loading="loading" :data="list" >
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <el-table-column label="图标" align="center" >
        <template slot-scope="scope">
          <img :src="baseUrl+scope.row.icon" style="width: 30px;height: 30px;" alt="">
          <!-- <image-preview v-if="scope.row.icon" :src="baseUrl+scope.row.icon" :width="50" :height="50"/> -->
        </template>
      </el-table-column>
      <el-table-column label="名称" align="center" prop="name" >
          <template slot-scope="scope">
            {{scope.row.name}}
            <i18n-input :objId="scope.row.id" type="com.ems.device.displayConfig" property="displayConfig.Name" slot="append"></i18n-input>
          </template>
      </el-table-column>
      <el-table-column label="默认值" align="center" prop="cmdValue" >
        <template slot-scope="scope">
          <span >{{ returnValue(scope.row) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="处理器" align="center" prop="handle" >
        <template slot-scope="scope">
          <span >{{scope.row.handle ? handleList.filter( o=> o.value == scope.row.handle)[0].name : null}}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleEdit(scope.row,scope.index)"
          >编辑</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 操作日志详细 -->
    <el-dialog title="新增控制按钮" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" label-width="120px" size="mini" :rules="rules" >
        <!-- <el-form-item label="类型名称" prop="name">
          <el-input v-model="form.name"  placeholder="请输入类型编号" />
        </el-form-item> -->
        <el-form-item label="控制按钮类型:" prop="model">
          <el-select v-model="form.model" :disabled="!!form.id"  placeholder="请选择控制按钮类型" @change="onModelChange" value-key="id" filterable>
            <el-option v-for="item in seriesList" :key="item.id"  :label="item.name" :value="item" :disabled="typeIds.includes(item.flag)"  />  
          </el-select>
        </el-form-item>
        <el-form-item label="图标:" prop="icon"   >
          <image-upload v-model="form.icon" :limit="1" />
        </el-form-item>
        <el-form-item label="名称:" prop="name">
          <el-input v-model="form.name"  placeholder="请输入名称" style="width: 300px;" >
            <i18n-input :objId="form.id" type="com.ems.device.displayConfig" property="displayConfig.Name" slot="append" v-if="form.id"></i18n-input>
          </el-input>
        </el-form-item>
        <el-form-item label="处理器:" prop="handle" v-if="this.queryParams.position=='station'">
          <el-select v-model="form.handle" placeholder="请选择处理器">
              <el-option v-for="item in handleList" :key="item.value"  :label="item.name" :value="item.value" />  
          </el-select>
        </el-form-item>
        <el-form-item label="执行时间区间:" prop="dateTime" v-if="form.model.displayModel==='time_interval'">
          <el-time-picker
            is-range
            v-model="form.dateTime"
            value-format="HH:mm:ss"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            placeholder="选择时间范围">
          </el-time-picker>
        </el-form-item>
        <el-form-item label="执行数值:" prop="slider" v-if="form.model.displayModel==='control_slider'">
          <el-input-number v-model="form.slider" style="width: 150px;" :min="parseInt(form.model.valueStart)" :max="parseInt(form.model.valueEnd)"  controls-position="right" ></el-input-number >
          <span class="value-unit" v-if="form.model.unit">{{ form.model.unit }}</span>
        </el-form-item>
        <!-- <el-form-item label="按钮:" v-if="form.model.displayModel==='control_btn'">
          
        </el-form-item> -->
        <el-form-item label="默认值:" prop="radio" v-if="form.model.displayModel==='control_ratio'">
          <div 
          v-for="sub in commandList"  
          :key="sub.id"
          @click="handleRadio(sub.value)"
          :class="['form-btn',form.radio===sub.value?'active-btn':'']"   
          >{{ sub.name }}</div>
        </el-form-item>
        <el-form-item label="执行内容:" prop="value" v-if="form.model.displayModel==='custom_btn'">
          <el-input v-model="form.value"  placeholder="请输入执行内容" />
        </el-form-item>
        <el-form-item label="运行时长:" prop="time" v-if="form.model.displayModel==='display_time_switch'">
          <el-time-picker
            v-model="form.time"
            :default-value="new Date(0, 0, 0, 0, 0, 10)"
            placeholder="运行时长">
          </el-time-picker>
        </el-form-item>
        <el-form-item label="执行项:" prop="radio" v-if="form.model.displayModel==='display_time_switch'">
          <div 
            v-for="sub in commandList"
            :key="sub.id"
            @click="handleRadio(sub.value)"
            :class="['form-btn',form.radio===sub.value?'active-btn':'']"   
            >{{ sub.name }}</div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="open = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {  listControlConfig,seriesIoOptions,seriesDetail,creatControlConfig,delControlConfig,configDetail,editControlConfig } from "@/api/device/deviceSensorConfig";
export default {
  data(){
    var validatePass = (rule, value, callback) => {
      console.log(value)
        if (!value||!value.flag) {
          callback(new Error('请选择控制按钮类型'));
        }else{
          callback()
        }
      };
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 表格数据
      list: [],
      handleList:[{name:"求和",value:"sumHandle"},{name:'平均值',value:'averageHandle'}],
      // 是否显示弹出层
      open: false,
      // 表单参数
      form: {
        model:{},
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name:''
      },
      // 表单校验
      rules: {
        model: [
          {  validator: validatePass,required: true, message: "请选择控制按钮类型", trigger: "change" }
        ],
        name: [
          { required: true, message: "名称不能为空", trigger: "blur" }
        ],
        handle: [
        { required: true, message: "处理器不能为空", trigger: "blur" }
        ],
        icon: [
          { required: true, message: "请上传图标", trigger: "blur" }
        ],
        dateTime: [
          { required: true, message: "时间区间不能为空", trigger: "blur" }
        ],
        slider: [
          { required: true, message: "执行数值不能为空", trigger: "blur" }
        ],
        radio: [
          { required: true, message: "请选择执行项", trigger: "blur" }
        ],
        time: [
          { required: true, message: "运行时长不能为空", trigger: "blur" }
        ],
        value: [
          { required: true, message: "执行内容不能为空", trigger: "blur" }
        ],
      },
      configData:{},
      seriesList:[],
      commandList:[],
      baseUrl:process.env.VUE_APP_BASE_API
    }
  },
  computed:{
    typeIds(){
      return this.list.map(i=>i.cmdFlag)
    },
    returnValue(){
      return (data)=>{
        if(!data.cmdValue){
          return ''
        }
        let list = data.commandList;
        let cmdValue = JSON.parse(data.cmdValue);
        let target = list.find(i=>i.value===cmdValue.value1);
        let name = '';
        if(data.displayModel==='time_interval'){
          name = cmdValue.value1+' - '+cmdValue.value2
        }else if(data.displayModel==='control_slider'){
          name = cmdValue.value1;
        }else if(data.displayModel==='control_ratio'){
          name = target.name
        }else if(data.displayModel==='custom_btn'){
          name = cmdValue.value1
        }else if(data.displayModel==='display_time_switch'){
          name = target.name+' - '+cmdValue.time
        }
        return name
      }
    }
  },
  created() {
    this.configData = this.$route.query
    this.queryParams.position = this.configData.position
    this.queryParams.deviceTypeId = this.configData.deviceTypeId
    this.getList();
    this.getSeriesIoOptions()
  },
  methods: {
    /** 查询数据 */
    getList() {
      this.loading = true;
      listControlConfig(this.queryParams).then( response => {
          this.list = response.rows;
          this.total = response.total;
          this.loading = false;
        }
      );
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const id = row.id || this.ids;
      this.$modal.confirm('是否确认删除"' + row.name + '"？').then(function() {
        return delControlConfig(id);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.form.position = this.configData.position;
      this.open = true;
      this.title = "添加设备类型";
    },
    // 表单重置
    reset() {
      this.form = {
        model:{},
        value:null,
        icon:'',
        position:null,
        radio:'',
        dateTime:'',
        time:'',
        slider:null,
        handle:null,
      };
      this.resetForm("form");
    },
    /**获取控制按钮**/
    getSeriesIoOptions(){
      let params = {
        sensorId:this.configData.sensorId,
        deviceTypeId:this.configData.deviceTypeId,
        control:this.configData.controlType
      }
      seriesIoOptions(params).then(res=>{
        this.seriesList = res.data;
      })
    },
    onModelChange(data){
      this.$set(this.form,'name',data.name)
      seriesDetail(data.id).then(res=>{
        this.commandList = res.data.commandList;
      })
    },
    handleRadio(data){
      this.$set(this.form,'radio',data)
    },
    submitForm(){
      console.log(this.form)
      let flag = this.form.model.flag||''
      let param = {};// 时间区间2个值，其他目前1个值
      let params = {
        "cmdFlag":flag,
        "deviceTypeId":this.form.model.deviceTypeId,
        "sensorId":this.form.model.id,
        "name":this.form.name,
        "icon":this.form.icon,
        "cmdValue":''  ,
        "handle" : this.form.handle
      }
      this.$refs["form"].validate(valid => {
        if (valid) {
          let displayModel = this.form.model.displayModel;
          if(displayModel==='time_interval'){
            if(this.form.dateTime&&this.form.dateTime.length>1){
              param.value1 = this.form.dateTime[0];
              param.value2 = this.form.dateTime[1];
            }
          }else if(displayModel==='control_slider'){
            param.value1 = this.form.slider;
          }else if(displayModel==='control_ratio'){
            param.value1 = this.form.radio
          }else if(displayModel==='custom_btn'){
            param.value1 = this.form.value
          }else if(displayModel==='display_time_switch'){
            let time = this.parseTime(this.form.time).substring(11,19)
            param.time = time
            param.value1 = this.form.radio
          }
          params.cmdValue = JSON.stringify(param);
          params.position = this.configData.position
          if (this.form.id != null) {
            params.id = this.form.id;
            editControlConfig(params).then(res=>{
              this.$modal.msgSuccess("保存成功");
              this.open = false;
              this.getList();
            })
          } else{
            creatControlConfig(params).then(res=>{
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            })
          }
        }
      })
    },
    handleEdit(row){
      configDetail(row.id).then(res=>{
        this.reset();
        this.form.model = this.seriesList.find(i=>i.id===res.data.sensorId);
        this.form.id = res.data.id;
        this.onModelChange(this.form.model)
        this.form.name = res.data.name;
        this.form.icon = res.data.icon;
        this.form.handle = res.data.handle;
        let displayModel = this.form.model.displayModel;
        let param = JSON.parse(res.data.cmdValue)
        if(displayModel==='time_interval'){
          this.form.dateTime = [param.value1,param.value2]
        }else if(displayModel==='control_slider'){
          this.form.slider = param.value1;
        }else if(displayModel==='control_ratio'){
          this.form.radio = param.value1;
        }else if(displayModel==='custom_btn'){
          this.form.value = param.value1;
        }else if(displayModel==='display_time_switch'){
          let time = param.time.split(':')
          this.form.time = new Date(0, 0, 0, time[0], time[1], time[2])
          this.form.radio = param.value1;
        }
        this.open = true;
      })
    }
  }
}
</script>

<style lang="scss" scoped >
.form-btn{
  display: inline-block;
  margin:4px 8px;
  padding: 4px 8px;
  border-radius: 3px;
  border: 1px solid #aaa;
  cursor: pointer;
  min-width: 50px;
  text-align: center;
  &.active-btn{
    border: 1px solid rgb(89, 156, 238);
    background-color: rgb(89, 156, 238);
    color: #fff;
  }
}
.config-name{
   margin:10px 0px 20px;
   font-size: 22px;
}
</style>